import re
import json
import urllib2
import cookielib

JSONSS_SERVICE = 1
JSONSS_METHOD = 2
JSONSS_PROPERTY = 3
JSONSS_EVENT = 4
JSONSS_INTERFACE = 5
JSONSS_FAULT = 6
JSONSS_RESPONSE = 7

JSONSS_METHOD_GET = "GET"
JSONSS_METHOD_SET = "SET"
JSONSS_METHOD_CALL = "CALL"
JSONSS_METHOD_PING = "PING"

from .proxy import JSONSSProxy

_http = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
_namere = re.compile("^[A-Za-z_]{1}[A-Za-z_0-9]*$")
_urlre = re.compile("^[A-Za-z_0-9~!:\\.,;()[\\]{}\\-]+$")

def proxyFromInterface (intf, url):
    return JSONSSProxy(intf, url)

def proxyFromText (jsons, url):
    return JSONSSProxy(json.loads(jsons), url)

def proxyFromUrl (url):
    try:
        resp = _http.open(url)
        return proxyFromText(resp.read(), url)
    except URLError as e:
        raise JSONSSError, (501, "Failed to get proxy: " + e.reason, None)
    except:
        raise JSONSSError, (501, "Failed to get proxy", None)
